<!--
	会计对账明细报表
-->
<template>
	<div class="m-view-accountMxReport m-window">
		<div class="m-condition" v-if="!showGoodsAccount">
      <el-form ref="ruleForm" 
        label-width="100px" 
        :inline-message="true" 
        label-position="left">
			  <el-row :gutter="10">
					<el-col :span="8">
						<el-form-item label="公司" class="rightItem">
							<el-select
								value-key="id"
								v-model="searchForm.companyCode"
								:placeholder="`请选择${label}`"
								@change="companyChange"
								ref="content"
								filterable
							>
								<el-option
									v-for="item in comOptions"
									:key="item.id"
									:label="item.companyName"
									:value="item.companyCode"
								></el-option>
							</el-select>
						</el-form-item>
					</el-col>

					<el-col :span="8">
						<el-form-item label="供应商" class="rightItem">
							<el-input
								placeholder="请选择供应商"
								v-model="searchForm.supplierName"
								clearable
								@focus="showSupplierDialog"
								readonly
								@mouseenter.native="mouseEnter"
								@mouseleave.native="mounseLeave">
								<el-button slot="append" icon="el-icon-search" @click="showSupplierDialog"></el-button>
								<span slot="suffix" @click="inputClearSon" class="m-cleanInput" v-show="inputClearBut">
									<i class="el-input_icon el-icon-circle-close el-input__clear"></i>
								</span>
							</el-input>
						</el-form-item>
					</el-col>
	
					<el-col :span="8">
						<el-form-item label="实物对账单号">
							<el-input v-model="searchForm.gooAccNo" placeholder="请输入对账单号" clearable></el-input>
						</el-form-item>
					</el-col>
			  </el-row>
			  <el-row :gutter="10">  
			  	<el-col :span="8">      
			  		<el-form-item label="申请日期" class="rightItem">
							<el-date-picker
								v-model="searchForm.applySd"
								placeholder="开始日期"
								value-format="yyyy-MM-dd"
								:clearable="false"
								:picker-options="pickerOptions">
              </el-date-picker>
			  		</el-form-item>
			  	</el-col>
			  	<el-col :span="5">
			  		<el-date-picker
							v-model="searchForm.applyEd"
							:clearable="false"
							placeholder="结束日期"
							value-format="yyyy-MM-dd"
							:picker-options="pickerOptions">
            </el-date-picker>
			  	</el-col>
          <el-col :span="8">
			  		<el-form-item label="会计对账单号">
			  			<el-input v-model="searchForm.accountNo" placeholder="请输入订单号" clearable></el-input>
			  		</el-form-item>
			  	</el-col>
			  	<el-col :span="2">
			  		<el-button type="primary" @click="searchReport(1)">查询</el-button>
			  	</el-col>
			  </el-row>
      </el-form>
		</div>
		<!--列表-->
		<div class="m-agTable m-bottom m-top2" v-if="!showGoodsAccount">
			<agGridComponents
				ref="reportGrid"
				:isColFit="isColFit"
				:getGridOptions="reportGridOptions"
				:getColumnDefs="reportColumnDefs">
      </agGridComponents>
		</div>
		<!-- 分页组件 -->
		<div class="m-page" v-if="!showGoodsAccount">
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				@prev-click="handlePrevClick"
				@next-click="handleNextClick"
				:current-page="pageInfo.current"
				:page-sizes="[30,50,100,150,200]"
				:page-size="pageInfo.size"
				layout="total, sizes, prev, pager, next, jumper"
				:total="pageInfo.total"
			></el-pagination>
		</div>
		<!-- 供应商弹窗 -->
		<el-dialog
			title="供应商信息"
			:visible.sync="srmSupplierDialogVisible"
			width="50%"
			:before-close="srmSupplierDialogClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false">
			<srmSupplierInfo ref="srmSupplierInfo" :layout="layout" @setSrmSupplierInfo="setSrmSupplierInfo"></srmSupplierInfo>
		</el-dialog>
    <!-- 审批意见 -->
    <el-dialog
			title="审批意见"
			:visible.sync="diaDetails"
			width="50%"
      :before-close="diaDetailsClose"
			v-dialogDrag
			:close-on-click-modal="false"
			:close-on-press-escape="false">
      
      <div class="card-wrap">
        <div class="card" v-for="(e, index) in examineDetaile" :key="index">
			    <div class="content">确认信息: {{e.message==""?'无':e.message}}</div>
          <div class="info">
            <p>确认人: {{e.confirmer}}</p>
            <p>确认时间: {{e.confirmDate}}</p>
          </div>
        </div>
      </div>
		</el-dialog>
    <!-- 调用实物对账单组件 -->
    <div class="m-window" v-if="showGoodsAccount">
      <goodsAccountReport :setClickValue="linkValue"></goodsAccountReport>
    </div>
	</div>
</template>

<script>
import _Api from "@/api"
import localeText from "@/i18n/agGridText";
import goodsAccountReport from "@/views/purchaseReport/goodsAccountReport"
import authInfo from "@/public/authInfo"
import Msg from "@/public/message"
import srmSupplierInfo from "@/components/srmSupplierInfo"
import agGridComponents from "@/components/agGridComponents"
import serviceTime from "@/public/serverTime"
import addOperation from "@/public/addOperation"
import Vue from 'vue';

const details = Vue.extend({
  template: `<span v-if="!params.node.data.flag">
      <el-button type="text" @click="details" class="rendererClass" size="mini">详情</el-button>
    </span>`,
  methods: {
    details () {
      this.params.context.componentParent.searchExamineDetail(this.params.value)
      this.params.context.componentParent.diaDetails = true;//
    },
  }
});
//
const btnLink = Vue.extend({
  template: `<span v-if="!params.node.data.flag">
      <el-button type="text" @click="details" class="rendererClass" size="mini">{{params.value}}</el-button>
    </span>`,
  methods: {
    details () {
      this.params.context.componentParent.linkValue.no = this.params.value;
      this.params.context.componentParent.showGoodsAccount = true;//
    },
  }
});
export default {
  components: {
    goodsAccountReport,
		srmSupplierInfo,
		agGridComponents
	},
	props:{
		setClickValue: '',
	},
	data () {
		return {
      inputClearBut: false,
      diaDetails: false,
      showGoodsAccount: false,
      examineDetaile:[],//审批意见
      linkValue:{
        no: ''
      },
			label: '',
			// 查询条件  
			searchForm: {
				companyCode: '',
				gooAccNo: '',
				accountNo: '',
				applySd: '',
				applyEd: '',
			},
			rowData: [],
			//表格是否自适应窗口宽度
			isColFit: true,
			//是否显示选择供应商弹窗
			srmSupplierDialogVisible: false,
			layout: {},
			comOptions: [],
			// 分页信息
			pageInfo: {
				current: 1,
				size: 30,
				total: 0
			},
			//   账户类型
			accountType: '',
			// 底部合计栏数据
			totalAmount: {
				invoiceMoney: 0
			},
			//日期设置
			pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
		}
	},
	beforeMount () {
		this.reportGridOptions = {
			context: { componentParent: this },
			animateRows: true, //排序动画
			enableFilter: true, //列过滤器
			enableSorting: true, //列排序
			enableCellChangeFlash: true,
			enableRangeSelection: true,
			enableColResize: true,
			localeText: localeText,
			pinnedBottomRowData: this.createData(1, 'Bottom'),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { 'color': 'red', 'font-weight': "bold" }
				}
				if (params.data.isMsExist == "1") {
					return { 'color': 'red' }
				}
			},
		}

		//   汇总报表-表格列信息
		this.reportColumnDefs = [
      { headerName: "操作", field: "accountNo", width: 70, cellRendererFramework: details},
			{ headerName: "会计对账单号", field: "accountNo", width: 160 },
			{ headerName: "申请日期",
				field: "applyDate",
				width: 100,
				cellRenderer: function (params) {
					if (params.value && params.value != "")
						return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
				}
      },
      { headerName: "审批状态", field: "examineState", width: 100, 
        cellRenderer: (params) => {
          if (!params.node.rowPinned) {
           if(params.value == 1) {
              return '新增';
            }else if(params.value == 2) {
              return '提交';
            }else if(params.value == 3) {
              return '确认';
            }else {
              return '审核';
            }
          }
        }
      },
      { headerName: "签署状态", field: "signState", width: 100, 
        cellRenderer: (params) => {
          if (!params.node.rowPinned) {
            if(params.value == 1) {
              return '未开始';
            }else if(params.value == 2) {
              return '签署中';
            }else {
              return '签署完成';
            }
          }  
        }
      },
      { headerName: "公司名称", field: "companyName", width: 180 },
      { headerName: "供应商名称", field: "supplierName", width: 180 },
      { headerName: "不符描述", field: "unConMemo", width: 180 },
      { headerName: "余额", field: "balance", width: 180 },
      { headerName: "业务类型", field: "busType", width: 180,
        cellRenderer: (params) => {
          if (!params.node.rowPinned) {
           if(params.value == 1) {
              return '普通采购';
            }else if(params.value == 2) {
              return '预付款';
            }else if(params.value == 3) {
              return '期初';
            }else {
              return '调整';
            }
          }
        } 
      },
      { headerName: "实物对账单号", field: "gooAccNo", width: 180, cellRendererFramework: btnLink},
      { headerName: "对账日期", field: "accountingDate", width: 180 },
      { headerName: "对账金额", field: "money", width: 180 },
      { headerName: "发票号码", field: "invoiceNo", width: 180 },
      { headerName: "发票日期", field: "invoiceDate", width: 180,
        cellRenderer: function (params) { 
          if (!params.node.rowPinned) {
				  	if (params.value && params.value != ""){
				  		return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format("yyyy-MM-dd");
            }
          }else if (params.value && params.value != ""){
            return params.value
          }
        }
      },
      { headerName: "发票金额", field: "invoiceMoney", width: 180 },
		]
	},
	mounted () {
    this.initDate();
	},

	methods: {
		// 查询实物对账报表数据
		searchReport (flag) {
			let validat = this.validatQuery(this.searchForm, this.searchType)
			if (flag) this.pageInfo.current = 1
			const { current, size } = this.pageInfo
      if (!validat) return
      delete this.searchForm.supplierName;
			let params = {
				...this.searchForm,
				current,
				size
			}
			this.$refs.reportGrid.loading = true
			// 获取报表数据   
			_Api.searchAccountMxReport(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.rowData = data.rows
					this.pageInfo.total = data.total
					this.rowData.forEach(row => {
						// 计算底部合计数据
						this.totalAmount.invoiceMoney = addOperation.accAdd(row.invoiceMoney||0, this.totalAmount.invoiceMoney)
					})
					this.$refs.reportGrid.gridOptions.api.setRowData(this.rowData)
					this.$refs.reportGrid.gridOptions.api.setPinnedBottomRowData(
						this.createData(1, "Bottom")
					)
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
			.catch(err => {
				this.$refs.reportGrid.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
		//根据单号获取数据
		getList(val){
			this.$refs.reportGrid.loading = true;
			this.pageInfo.current = 1;
			const { current, size } = this.pageInfo
			let params = {
				accountNo: val.no,
				current,
				size
			}
			// 获取报表数据   
			_Api.searchAccountMxReport(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.rowData = data.rows
					this.pageInfo.total = data.total
					this.rowData.forEach(row => {
						// 计算底部合计数据
						this.totalAmount.invoiceMoney = addOperation.accAdd(row.invoiceMoney, this.totalAmount.invoiceMoney)
					})
					this.$refs.reportGrid.gridOptions.api.setRowData(this.rowData)
					this.$refs.reportGrid.gridOptions.api.setPinnedBottomRowData(
						this.createData(1, "Bottom")
					)
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
			.catch(err => {
				this.$refs.reportGrid.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
    //查询审批意见
    searchExamineDetail(val){
			let params = {
				accountNo: val
			}
			// 获取报表数据   
			_Api.getExamineDetail(params).then(({ data }) => {
				this.$refs.reportGrid.loading = false
				if (data.code === 1) {
					this.examineDetaile = data.rows;
				} else {
					Msg.showErrorMsg(data.info)
				}
			})
				.catch(err => {
					this.$refs.reportGrid.loading = false
					Msg.showErrorMsg(err.data.message)
				})
    },
		//  验证查询参数
		validatQuery (params, type) {
			const {
				companyCode, //公司编码
				applySd, //申请开始日期
				applyEd,  //申请结束日期
			} = params
			if (!companyCode) {
				Msg.showPopMsg(`请选择公司和填写日期`)
				return false
			} 
			return true
		},
		// 选择公司回调
		companyChange (val) {
			//if (this.accountType == 1) {
				this.layout.companyCode = val
				this.layout.auth = true
				this.searchForm.supplierCode = ""
				this.searchForm.supplierName = ""
			//}
		},
		// 输入框清除事件监听
		inputClearSon () {
			this.searchForm.supplierName = ""
			this.searchForm.supplierCode = ""
			this.inputClearBut = false
		},
		// 回显选择的供应商信息
		setSrmSupplierInfo (msg) {
			if (msg.length > 0) {
				const { supplierCode, supplierName } = msg[0]
				this.srmSupplierDialogVisible = false
				this.searchForm.supplierCode = supplierCode
				this.searchForm.supplierName = supplierName
			}
		},
		// 打开供应商弹窗
		showSupplierDialog () {
			let that = this;
			if (!this.layout.companyCode) {
				this.$alert(`提示：请选择${this.label}！`, {
					showClose: false,
					confirmButtonText: "确定",
					customClass: "alertPrompt"
				})
				this.$refs.content.focus()
				return
			} else {
				this.srmSupplierDialogVisible = true
				this.$nextTick(_ => {
					that.$refs.srmSupplierInfo.search()
				})
			}
		},
		// 关闭供应商弹窗回调
		srmSupplierDialogClose (done) {
			this.$refs.srmSupplierInfo.keyWord = ""
			this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
				this.$refs.srmSupplierInfo.keyWord
			)
			done()
    },
    //关闭审批意见弹窗回调
    diaDetailsClose(done){
      done();
    },
		// 供应商输入框鼠标移入事件监听
		mouseEnter () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = true
		},
		// 供应商输入框鼠标移出事件监听
		mounseLeave () {
			const { supplierName } = this.searchForm
			if (supplierName) this.inputClearBut = false
		},
		// 每页条数改变回调
		handleSizeChange (size) {
			this.pageInfo.size = size
			this.pageInfo.current = 1
			this.searchReport()
		},
		// 页码改变回调
		handleCurrentChange (current) {
			this.pageInfo.current = current
			this.searchReport()
		},
		// 点击上一页回调
		handlePrevClick (current) {
			this.pageInfo.current = current
		},
		// 点击下一页回调
		handleNextClick (current) {
			this.pageInfo.current = current
		},
		// 根据账户类型获取公司下拉列表
		getCompanyOption () {
			authInfo.getAuthInfo().then(data => {
				this.comOptions = data
				this.searchForm.companyCode = data[0].companyCode
				//this.searchForm.companyName = data[0].companyName
				this.layout.companyCode = data[0].companyCode
				this.layout.auth = true
				//用来查询从会计明细报表跳转过来查询单号的信息
				if(this.setClickValue && this.setClickValue != ""){
					this.getList(this.setClickValue);
					return
				}
				this.searchReport(1)
			})
				.catch(err => {
					//后面加的,用来查询从会计明细报表跳转过来查询单号的信息
					if(this.setClickValue && this.setClickValue != ""){
						this.getList(this.setClickValue);
						return
					}
					Msg.showErrorMsg(err)
				});
		},
		// 初始化查询时间
		initDate () {
			// 日期范围默认30天内
			serviceTime.getServiceTime().then((serviceTime) => {
				let startDate = new Date(serviceTime.getTime() - 3600 * 1000 * 24 * 30 * 3).Format('yyyy-MM-dd')
				let endDate = serviceTime.Format("yyyy-MM-dd")
				this.searchForm.applySd = startDate
				this.searchForm.applyEd = endDate
				this.getCompanyOption();
			}).catch(err => {
				Msg.showErrorMsg(err)
			})
		},
		// 创建底部合计栏
		createData (count, prefix) {
			let result = []
			for (let i = 0; i < count; i++) {
				const invoiceMoney  = this.totalAmount.invoiceMoney;
				result.push({
					invoiceDate: "合计",
          invoiceMoney,
          flag: true//true,即为底部行
				})
      }
			return result;
		},
	},
}
</script>

<style lang="less">
.m-view-accountMxReport {
	.el-form {
		.el-form-item {
			margin-bottom: 0;
		}
  }
  .card-wrap{
    padding-bottom: 20px;
    max-height: 400px;
    overflow-y: auto;
    .card{
      margin: 12px 15px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
      .content{
        margin: 0 20px;
        line-height: 50px;
        word-break: break-all;
      }
      .info{
        margin: 0 20px;
        padding-bottom: 10px;
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
</style>